import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/generated/json/base/json_convert_content.dart';
import 'package:yurun_smartmerchants/models/category_good_entity.dart';
import 'package:yurun_smartmerchants/models/good_list_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/routes/routes.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';
import 'package:yurun_smartmerchants/view/EmptyView.dart';
import 'package:yurun_smartmerchants/view/custom_loadmore_footer.dart';
import 'package:yurun_smartmerchants/view/custom_refresh_header.dart';

class InventoryManagementPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _InventoryManagementPageState();
  }
}

class _InventoryManagementPageState extends State<InventoryManagementPage> {
  bool empty = false;
  bool selected = false;
  int currentIndex = 0;
  int currentCategoryId;
  int page = 0;
  final int size = 15;
  bool isRefreshOrLoad = false;
  EasyRefreshController _easyRefreshController = EasyRefreshController();

  List<CategoryGoodEntity> categoryList = List();
  List<GoodListContent> goodList = List();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _getCategoryGood();
    });
  }

  void statusRefreshLoad(load,last){
    if(page == 0){
      _easyRefreshController.finishRefresh(success: load);
    }
    _easyRefreshController.finishLoad(success: load,noMore: last);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colours.white,
        centerTitle: true,
        iconTheme: IconThemeData(color: Colours.app_words),
        title: Text(
          '库存管理',
          style: TextStyle(fontSize: 18, color: Colours.app_words),
        ),
      ),
      body: CupertinoScrollbar(child: Container(
        color: Colours.app_background,
        child: Row(
          children: <Widget>[
            Container(
              color: Color(0Xffefefef),
              width: AppSize.width(157),
              child: ListView.builder(
                  itemCount: categoryList.length,
                  itemBuilder: (BuildContext context, int index) {
                    if (index == currentIndex) {
                      selected = true;
                    } else {
                      selected = false;
                    }
                    return _leftItem(index);
                  }),
            ),
            Container(
              width: AppSize.width(1),
              color: Color(0xffefefef),
            ),
            Expanded(
                child: Container(
                  color: Colors.white,
                  child: CupertinoScrollbar(
                      child: EasyRefresh(
                          controller: _easyRefreshController,
                          header: CustomRefreshHeader(),
                          footer: CustomLoadFooter(),
                          emptyWidget: empty ? EmptyView(content: '暂无数据',) : null,
                          onRefresh: () async {
                            isRefreshOrLoad = true;
                            page = 0;
                            _getGoodsList(currentCategoryId);
                          },
                          onLoad: () async {
                            isRefreshOrLoad = true;
                            page ++;
                            _getGoodsList(currentCategoryId);
                          },
                          child: ListView.separated(
                              itemBuilder: (BuildContext context, int index) {
                                return _rightItem(index);
                              },
                              separatorBuilder: (BuildContext context, int index) {
                                return Divider(
                                  height: AppSize.height(1),
                                  thickness: AppSize.height(1),
                                  color: Color(0xffefefef),
                                );
                              },
                              itemCount: goodList.length)
                      )
                  ),
                ))
          ],
        ),
      )),
    );
  }

  Widget _leftItem(index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          currentIndex = index;
        });
        currentCategoryId = categoryList[index].id;
        _getGoodsList(currentCategoryId);
//        showToast('index:$index');
      },
      child: Container(
        height: AppSize.height(120),
        child: Row(
          children: <Widget>[
            Offstage(
              offstage: !selected,
              child: Container(
                color: Color(0xffdd4b39),
                width: AppSize.width(5),
              ),
            ),
            Expanded(
                child: Container(
                  alignment: Alignment.center,
                  color: selected ? Colours.white : Color(0Xffefefef),
                  child: Text(
                    categoryList[index].name,
                    style: TextStyle(
                        fontSize: AppSize.sp(28),
                        color: selected ? Color(0xffdd4b39) : Color(0xff626262)),
                  ),
                ))
          ],
        ),
      ),
    );
  }

  Widget _rightItem(index) {
    return Material(
      color: Colors.white,
      child: InkWell(
        onTap: () {
          Navigator.pushNamed(context, inventory_detail_page,arguments: goodList[index]);
        },
        child: Container(
          height: AppSize.height(147),
          child: Row(
            children: <Widget>[
              Container(
                width: AppSize.height(147),
                padding: EdgeInsets.all(AppSize.height(15)),
                child: Image.network(
                  goodList.length == 0 ? '' : goodList[index].url,
                  fit: BoxFit.cover,
                ),
              ),
              Container(
                width: AppSize.width(170),
                alignment: Alignment.centerLeft,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                        goodList.length == 0 ? '' : goodList[index].categoryiiiName,
                        style: TextStyle(fontSize: AppSize.sp(32), color: Colours.color_313131,),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1
                    ),
                    Container(
                      margin: EdgeInsets.only(top: AppSize.height(10),right: AppSize.width(5)),
                      padding: EdgeInsets.only(left: AppSize.width(5),right: AppSize.width(5),bottom: AppSize.height(2)),
                      decoration: ShapeDecoration(
                          color: Color(0xffefefef),
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.all(
                                  Radius.circular(AppSize.height(5))))),
                      child: Text(
                        goodList.length == 0 ? '' : goodList[index].quantity + goodList[index].packageUnit + '/' + goodList[index].packageContainer,
                        style: TextStyle(fontSize: AppSize.sp(24), color: Color(0xff434343)),
                        overflow: TextOverflow.ellipsis,maxLines: 1,),
                    ),
                  ],
                ),
              ),
              Expanded(
                  child: Container(
                    height: AppSize.height(147),
                    alignment: Alignment.bottomLeft,
                    padding: EdgeInsets.only(bottom: AppSize.height(36),right: AppSize.width(30)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        ConstrainedBox(
                          constraints: BoxConstraints(
                            maxWidth: AppSize.width(150),
                          ),
                          child: Text(
                              goodList.length == 0 ? '' : '库存' + goodList[index].inventory +'公斤',
                              style: TextStyle(fontSize: AppSize.sp(26), color: goodList.length != 0 && (goodList[index].inventory == null || goodList[index].inventory.isEmpty) ? Color(0xff626262) : Color(0xffeb3323)),
                              overflow: TextOverflow.ellipsis,maxLines: 1,),
                        ),
                        Padding(padding: EdgeInsets.only(top: AppSize.height(2)),child: Icon(Icons.arrow_forward_ios,color: Color(0xffaaaaaa),size: AppSize.sp(26),),)
                      ],
                    ),
                  )),
            ],
          ),
        ),
      ),
    );
  }

  void _getCategoryGood(){
    ApiInterface.getCategoryGood().then((value){
      value.forEach((f){
        CategoryGoodEntity categoryGoodEntity = JsonConvert.fromJsonAsT<CategoryGoodEntity>(f);
        categoryList.add(categoryGoodEntity);
      });
      currentCategoryId = categoryList[0].id;
      _getGoodsList(currentCategoryId);
    });
  }

  void _getGoodsList(id){
    if(!isRefreshOrLoad){
      LoadingUtil.showLoading(context,tip: '加载中...');
    }
    ApiInterface.getGoodsList(id, page, size).then((value){
      GoodListEntity goodListEntity = JsonConvert.fromJsonAsT<GoodListEntity>(value);
      setState(() {
        if(page == 0){
          goodList.clear();
        }
        if(goodListEntity.content != null && goodListEntity.content.length > 0){
          goodList.addAll(goodListEntity.content);
        }
        if(goodList.length == 0){
          empty = true;
        }else{
          empty = false;
        }
      });
      statusRefreshLoad(true, goodListEntity.last);
      if (goodList.length > 0) {
        if (isRefreshOrLoad && page == 0) {
          showToast("刷新成功");
        } else if (goodListEntity.last && page > 0) {
          showToast("暂无更多数据");
        }
      }
    }).catchError((error){
      statusRefreshLoad(false, true);
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }
}
